public class WeatherApp {
    private UserPreferences userPreferences = new UserPreferences();
    private ForecastHistory forecastHistory = new ForecastHistory();
    private NotificationManager notificationManager = new NotificationManager();
    private MultiAPIManager multiAPIManager; // 使用多源API管理器
    private SocketWeatherServer socketServer; // 添加套接字服务器实例

    public WeatherApp() {
        // 初始化多源API管理器
        initializeMultiAPIManager();
    }
    
    /**
     * 初始化多源API管理器
     */
    private void initializeMultiAPIManager() {
        // 启动备份套接字服务器
        socketServer = new SocketWeatherServer();
        socketServer.start();
        
        multiAPIManager = new MultiAPIManager(userPreferences);
        
        // 注册主要API服务
        WeatherAPIManager openWeatherService = new WeatherAPIManager(userPreferences);
        multiAPIManager.registerAPIService(openWeatherService);
        
        WeatherAPIComService weatherApiComService = new WeatherAPIComService(userPreferences);
        multiAPIManager.registerAPIService(weatherApiComService);
        
        // 注册基于套接字的备份服务器
        SocketWeatherAPIService socketBackupService = new SocketWeatherAPIService(userPreferences);
        multiAPIManager.registerAPIService(socketBackupService);
        
        // 设置聚合策略
        String strategyName = userPreferences.getAggregationStrategy();
        MultiAPIManager.AggregationStrategy strategy;
        try {
            strategy = MultiAPIManager.AggregationStrategy.valueOf(strategyName);
        } catch (IllegalArgumentException e) {
            strategy = MultiAPIManager.AggregationStrategy.PRIMARY_FAILOVER;
        }
        multiAPIManager.setAggregationStrategy(strategy);
        
        System.out.println("Multi-API Manager initialized with " + 
            multiAPIManager.getRegisteredServices().size() + " services including socket backup");
    }
    
    /**
     * 重新初始化API管理器（当API配置更改时调用）
     */
    public void reinitializeAPIManager() {
        if (multiAPIManager != null) {
            multiAPIManager.shutdown();
        }
        initializeMultiAPIManager();
    }

    public String displayWeather(Location location) {
        WeatherData currentWeather = multiAPIManager.getCurrentWeather(location);
        if (currentWeather != null) {
            forecastHistory.addForecast(currentWeather);
            notificationManager.checkAndSendWeatherAlert(currentWeather);
            return currentWeather.toString();
        } else {
            return "无法获取天气数据。请检查API配置和网络连接。";
        }
    }

    public String displayForecast(Location location, int days) {
        WeatherData[] forecast = multiAPIManager.getForecast(location, days);
        if (forecast != null && forecast.length > 0) {
            StringBuilder result = new StringBuilder();
            for (WeatherData data : forecast) {
                forecastHistory.addForecast(data);
                notificationManager.checkAndSendWeatherAlert(data);
                result.append(data.toString()).append("\n\n");
            }
            return result.toString();
        } else {
            return "无法获取天气预报数据。请检查API配置和网络连接。";
        }
    }

    public UserPreferences getUserPreferences() {
        return userPreferences;
    }

    /**
     * 获取多源API管理器
     */
    public MultiAPIManager getMultiAPIManager() {
        return multiAPIManager;
    }
    
    /**
     * 获取API管理器（保持向后兼容性）
     * @deprecated 使用 getMultiAPIManager() 替代
     */
    @Deprecated
    public WeatherAPIManager getApiManager() {
        // 返回第一个注册的OpenWeatherMap服务
        for (WeatherAPIService service : multiAPIManager.getRegisteredServices()) {
            if (service instanceof WeatherAPIManager) {
                return (WeatherAPIManager) service;
            }
        }
        // 如果没有找到，创建一个新的
        return new WeatherAPIManager(userPreferences);
    }
    
    /**
     * 关闭应用程序时清理资源
     */
    public void shutdown() {
        if (multiAPIManager != null) {
            multiAPIManager.shutdown();
        }
        if (socketServer != null) {
            socketServer.stop();
        }
    }
}
